package service

import (
	"gomain/app/model"

	"github.com/gogf/gf/v2/frame/g"
)

var Product = productService{}

type productService struct{}

func (s *productService) List(page, limit int) ([]model.Product, int, error) {
	var products []model.Product

	m := g.DB().Model("products")
	count, err := m.Count()
	if err != nil {
		return nil, 0, err
	}

	err = m.Page(page, limit).
		LeftJoin("categories", "products.category_id = categories.id").
		Fields("products.*, categories.name as category_name").
		Scan(&products)
	return products, count, err
}

func (s *productService) Add(product *model.Product) error {
	_, err := g.DB().Model("products").Data(product).Insert()
	return err
}

func (s *productService) Update(product *model.Product) error {
	_, err := g.DB().Model("products").Data(product).Where("id=?", product.Id).Update()
	return err
}

func (s *productService) Delete(id int) error {
	_, err := g.DB().Model("products").Where("id=?", id).Delete()
	return err
}
